package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 定时处理未支付的超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOutOrder() {
        log.info("定时处理超时订单");
        List<Orders> list = orderMapper.selectOrderTimeOutAndStatus
                            (Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(15));
        if(list != null && list.size() > 0) {
            list.forEach(item -> {
                item.setStatus(Orders.CANCELLED);
                item.setCancelTime(LocalDateTime.now());
                item.setCancelReason("订单超时未支付");
                orderMapper.updateOrders(item);
            });
        }
    }
    @Scheduled(cron = "0 0 1 * * ?")
    public void OrderDeliveryTimeOut() {
        log.info("定时处理派送超时订单");
        List<Orders> list = orderMapper.selectOrderTimeOutAndStatus
                (Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusHours(-1));
        if(list != null && list.size() > 0) {
            list.forEach(item -> {
                item.setStatus(Orders.COMPLETED);
                orderMapper.updateOrders(item);
            });
        }
    }
}
